<script setup lang="ts">
import { reactive, onMounted } from 'vue'
import _ from 'lodash'
import $time from '@/utils/time'

const emit = defineEmits(['change'])

const props = defineProps({
  show: {
    type: Boolean,
    default: () => false
  }
})

const state = reactive({
  startTime: 0,
  endTime: 0,
  step: '00:15',
  cycle: 900,
  timeList: [] as any,
  startList: [] as any,
  endList: [] as any,
  cycleList: [
    {
      value: 900,
      label: '15分钟'
    },
    {
      value: 1800,
      label: '30分钟'
    },
    {
      value: 3600,
      label: '60分钟'
    }
  ]
})

const changeTime = () => {
  filterList()
  emit('change', {
    cycle: state.cycle,
    startTime: $time.formatTimeStamp(state.startTime, 'HH:mm:00'),
    endTime: $time.formatTimeStamp(state.endTime, 'HH:mm:00')
  })
}

const filterList = () => {
  state.startList = _.filter(_.cloneDeepWith(state.timeList), (o) => {
    return o.value < state.endTime
  })

  state.endList = _.filter(_.cloneDeepWith(state.timeList), (o) => {
    return o.value > state.startTime
  })
}

const changeCycle = () => {
  initData()
}

const initData = () => {
  state.timeList = []
  let startTime = $time.getTimeStamp($time.getCurrentDate() + ' 00:00:00')
  state.startTime = startTime
  const endTime = $time.getTimeStamp($time.getCurrentDate() + ' 23:59:00')
  state.endTime = endTime
  while (startTime < endTime) {
    const obj = {
      value: startTime,
      label: $time.formatTimeStamp(startTime, 'HH:mm')
    }
    state.timeList.push(obj)
    startTime += state.cycle
  }

  state.timeList.push({
    value: endTime,
    label: $time.formatTimeStamp(endTime, 'HH:mm')
  })

  filterList()

  emit('change', {
    cycle: state.cycle,
    startTime: $time.formatTimeStamp(startTime, 'HH:mm:00'),
    endTime: $time.formatTimeStamp(endTime, 'HH:mm:00')
  })
}

onMounted(() => {
  initData()
})
</script>

<template>
  <div class="flex flex-row items-center justify-start">
    <el-select-v2
      class="!w-[100px]"
      v-model="state.startTime"
      filterable
      :popper-append-to-body="true"
      :teleported="false"
      :options="state.startList"
      placeholder="请选择周期"
      value-key="value"
      @change="changeTime"
    />

    <el-select-v2
      class="!w-[100px] mx-2"
      v-model="state.endTime"
      filterable
      :popper-append-to-body="true"
      :teleported="false"
      :options="state.endList"
      placeholder="请选择周期"
      value-key="value"
      @change="changeTime"
    />

    <el-select-v2
      v-if="props.show"
      class="!w-[100px]"
      v-model="state.cycle"
      filterable
      :popper-append-to-body="true"
      :teleported="false"
      :options="state.cycleList"
      placeholder="请选择周期"
      value-key="value"
      @change="changeCycle"
    />
  </div>
</template>

<style lang="scss" scoped></style>
